package com.dong.repeatsubmit;

import com.dong.repeatsubmit.cache.CacheUtil;
import com.dong.repeatsubmit.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@Slf4j
public class SubmitTest implements ApplicationRunner {
    @Autowired
    RestTemplate restTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        log.info("多个线程测试接口提交");
//        String url = "http://localhost:8080/user/v1/create";
//        CountDownLatch countDownLatch = new CountDownLatch(1);
//        ExecutorService executorService = Executors.newFixedThreadPool(10);
//        HttpEntity request = buildRequest();
//        for (int i = 0; i < 10; i++) {
//            executorService.submit(()->{
//                try {
//                    countDownLatch.await();
//                    log.info("Thread:{},time:{}",Thread.currentThread().getName(),System.currentTimeMillis());
//                    ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
//                    log.info("Thread:{},body:{}",Thread.currentThread().getName(),response.getBody());
//                } catch (InterruptedException e) {
//                    log.info("请求发送错误:{}",e);
//                }
//            });
//        }
//        countDownLatch.countDown();
        User user = new User();
        user.setAge(666);
        user.setSex(2);
        user.setUserName("亚东");
        CacheUtil.put("user",user);
    }

    private HttpEntity buildRequest() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        String token = UUID.randomUUID().toString().replace("-", "");
        httpHeaders.set("Authorization",token);
        Map<String,String> body = new HashMap<>();
        body.put("userId","10001");
        return new HttpEntity(body,httpHeaders);
    }


    public static void main(String[] args) {
        Thread t1 = new Thread();
        t1.setName("thread one");

        Thread t2 = new Thread();
        t2.setName("thread two");

        t1.start();
        t1.run();

        try {
            t1.join(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t1.interrupt();
    }


}
